<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="disabled">
      <a-form-model layout="horizontal" ref="subForm" slot="detail" :model="model" :rules="validatorRules"
        v-bind="formItemLayout">
        <z-form-item :datas="fieldArr" :form="model" :rules="validatorRules" :gutter="0" @change="getChange">
          <!--//自定义戒毒所-->
          <template slot="slots-detoxificationCenterId">
            <j-select-depart v-model="model.detoxificationCenterId" :orgCategory="3" :trigger-change="true"
              :multi="false" @rows="getSelectRows('detoxificationCenter', $event)" />
          </template>
          <!--//自定义中止机构-->
          <template slot="slots-abortOrganId">
            <j-select-depart v-model="model.abortOrganId" :orgCategory="2" :trigger-change="true" :multi="false"
              @rows="getSelectRows('abortOrgan', $event)" />
          </template>
        </z-form-item>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { abortApply } from '@/api/sjsk/personService'
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {},
      confirmLoading: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      fieldArr: [
        { label: '姓名', prop: 'name', tagType: 'input', disabled: true },
        { label: '身份证号', prop: 'identityCard', tagType: 'input', disabled: true },
        { label: '中止开始时间', prop: 'abortStartDate', tagType: 'date-picker', format: 'YYYY-MM-DD', showTime: false },
        // {label: '中止结束时间', prop: 'abortEndDate', tagType: 'date-picker', format: 'YYYY-MM-DD', showTime: false},
        { label: '预计中止天数', prop: 'abortDays', tagType: 'input', disabled: false },
        { label: '中止原由', prop: 'abortReason', tagType: 'dict-select', dictCode: 'abort_reason' },
        { label: '申请自愿戒毒原因', prop: 'detoxificationReason', tagType: 'input', toggle: false },
        { label: '戒毒所', prop: 'detoxificationCenterId', toggle: false },
        { label: '中止机构', prop: 'abortOrganId', toggle: false },
        { label: '采取措施', prop: 'soerciveMeasures', tagType: 'dict-select', dictOptions: [{ text: '刑拘', value: '1' }, { text: '逮捕', value: '2' }], toggle: false },
        { label: '备注', prop: 'remark', tagType: 'textarea', },
        { label: '证明材料', prop: 'file', tagType: 'upload-file', fileDescribe: '可上传多个文件', fileFormat: '.doc,.docx,.xls,.xlsx,.pdf,.jpg,.jpeg,.png' },
      ],
      validatorRules: {
        abortStartDate: [{ required: true, message: '请选择中止开始时间' }],
        // abortEndDate:[ { required: true, message: '请选择中止结束时间' }],
        abortReason: [{ required: true, message: '请选择中止原由' },],
        detoxificationReason: [{ required: true, message: '请选择申请自愿戒毒原因' },],
        detoxificationCenterId: [{ required: true, message: '请选择戒毒所' },],
        abortOrganId: [{ required: true, message: '请选择中止机构' },],
        soerciveMeasures: [{ required: true, message: '请选择采取措施' },],
      }
    }
  },
  computed: {
    props() {
      let prop1 = ['detoxificationReason', 'detoxificationCenterId'] //戒毒所
      let prop2 = ['abortOrganId', 'soerciveMeasures'] // 中止机构、采取措施
      let arrProp1 = [...this.fieldArr].filter(x => [...prop1].some(y => y === x.prop))
      let arrProp2 = [...this.fieldArr].filter(x => [...prop2].some(y => y === x.prop))
      return [{ val: '1', arrProp: arrProp1 }, { val: '2', arrProp: arrProp2 }]
    }
  },
  watch: {
    'model.abortReason': {
      immediate: true,
      deep: true,
      handler(val) {
        this.props.forEach(item => {
          if (item.val && item.val == val) {
            item.arrProp.forEach(item => item.toggle = true)
          } else {
            item.arrProp.forEach(item => item.toggle = false)
          }
        })
      }
    }
  },
  methods: {
    show(record) {
      // this.model = record?Object.assign({}, record):this.model;
      this.$set(this.model, 'sjskPersonId', record.id)
      this.$set(this.model, 'name', record.realName)
      this.$set(this.model, 'identityCard', record.identityCard)
    },
    submitForm() {
      const parameter = Object.assign({}, this.model)
      this.$refs.subForm.validate((valid) => {
        if (valid) {
          abortApply(parameter)
            .then(res => {
              this.confirmLoading = false
              if (res.success) {
                this.$message.success(res.message)
                this.$emit('ok');
              } else {
                this.$message.warn(res.message)
              }
            })
            .catch(e => {
              this.$message.warn('请求失败！')
              this.confirmLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 戒毒所、中止机构
    getSelectRows(prop, rows) {
      console.log(prop, rows)
      let adminDivisionStrs = rows && rows.length > 0 ? rows.map(v => v.adminDivisionStr).join(',') : ''
      let titles = rows && rows.length > 0 ? rows.map(v => v.title).join(',') : ''
      console.log(adminDivisionStrs, titles)
      // 戒毒所
      if (prop === 'detoxificationCenter') {
        this.$set(this.model, 'detoxificationCenter', titles)
        this.$set(this.model, 'detoxificationCenterLeval', adminDivisionStrs)
      }
      // 中止机构
      if (prop === 'abortOrgan') {
        this.$set(this.model, 'abortOrgan', titles)
        this.$set(this.model, 'abortOrganLeval', adminDivisionStrs)
      }
    },
    getChange(prop, value) {
      if (prop === 'abortStartDate') {
        this.onDateChangeNew(1, ['abortStartDate', 'abortEndDate'], ['中止开始时间', '中止结束时间'])
      }
      if (prop === 'abortEndDate') {
        this.onDateChangeNew(2, ['abortStartDate', 'abortEndDate'], ['中止开始时间', '中止结束时间'])
      }
    },
    // 两时间校验
    onDateChangeNew(val, time, message) {
      if (!val && !time && !message) return
      let startTime = time[0]
      let endTime = time[1]
      let startMessage = message[0]
      let endMessage = message[1]
      let flag = this.dateCompare(this.model[startTime], this.model[endTime])
      if (flag && this.model[startTime] !== this.model[endTime]) {
        if (val == 1) {
          // this.$refs['subForm'].validateField('abortStartDate')
          this.$message.warning(startMessage + "等于不能小于" + endMessage)
          this.$set(this.model, startTime, '')
        } else {
          // this.$refs['subForm'].validateField('abortEndDate')
          this.$message.warning(endMessage + "必须大于或等于" + startMessage)
          this.$set(this.model, endTime, '')
        }
      }
      // 外出请假记录---计算外出天数
      if (this.model.abortStartDate && this.model.abortEndDate) {
        this.$set(this.model, 'abortDays', this.getDaysBetween(this.model.abortStartDate, this.model.abortEndDate))
      } else {
        this.$set(this.model, 'abortDays', '')
      }
    },
    //比较两个日期大小
    dateCompare(startDate, endDate) {
      if (
        startDate == "" ||
        endDate == "" ||
        startDate == undefined ||
        endDate == undefined ||
        startDate == null ||
        endDate == null
      )
        return;
      const aStart = startDate.split("-"); //转成成数组，分别为年，月，日，下同
      const aEnd = endDate.split("-");
      const startDateTemp = aStart[0] + "/" + aStart[1] + "/" + aStart[2];
      const endDateTemp = aEnd[0] + "/" + aEnd[1] + "/" + aEnd[2];
      if (startDateTemp >= endDateTemp) return true;
      else return false;
    },
    /**
     * 计算两个日期之间的天数
     * @param dateString1  开始日期 yyyy-MM-dd
     * @param dateString2  结束日期 yyyy-MM-dd
     * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期，返回0
     */
    getDaysBetween(dateString1, dateString2) {
      const startDate = Date.parse(dateString1);
      const endDate = Date.parse(dateString2);
      if (startDate > endDate) {
        return 0;
      }
      if (startDate == endDate) {
        return 1;
      }
      const days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      return days;
    }
  }
}
</script>
